package replica;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import client.CommandClient;
import udp.UdpClient;
import udp.UdpServer;
import udp.message.ReportReplicaMessage;
import udp.message.StartLibraryMessage;
import udp.message.SyncLibraryDatabaseMessage;
import udp.message.UdpMessage;
import util.ConfigurationHelper;

public class ReplicaManagerUdpServer extends UdpServer {

	HashMap<String, ReplicaInformation> replicas;
	
	
	public ReplicaManagerUdpServer() { 
		super("manager", ConfigurationHelper.getIntProperty("manager.port"));
		
		String[] replicaIDs = {"r1","r2","r3","r4"};
		
		this.replicas = new HashMap<String, ReplicaInformation>();
		
		for(String r:replicaIDs) {
			
			UdpClient toReplica = null;
			try {
				toReplica = new UdpClient(ConfigurationHelper.getProperty(r+".replica.host"), ConfigurationHelper.getIntProperty(r+".replica.port"));
			} catch (SocketException | UnknownHostException e) {
				System.out.println("Error: " +e.getMessage());
				e.printStackTrace();
			}
			StartLibraryMessage message = new StartLibraryMessage();
			System.out.print("Sending StartLibaryMessage to "+r+" replica @"+ConfigurationHelper.getProperty(r+".replica.host")+"...");
			toReplica.send(message);

			System.out.print("Done.\n");
			
			this.replicas.put(ConfigurationHelper.getProperty(r+".replica.host"), new ReplicaInformation(r));
		}
	}

	@Override
	public void receiveMessage(UdpMessage message) {
		if(message instanceof ReportReplicaMessage) {
			
			ReportReplicaMessage report = (ReportReplicaMessage) message;
			
			String erroneousReplica = report.getErroneousReplicaId();
			System.out.println("Replica: "+erroneousReplica+" is not responding.");
			
			String erroneousHost = ConfigurationHelper.getProperty(erroneousReplica+".replica.host");
			
			ReplicaInformation ri = this.replicas.get(erroneousHost);
			if(ri.increaseErrorCount() >= 3) {
				System.out.println("["+erroneousReplica+"] must be restarted.");
				this.syncFaultyReplica(erroneousHost, ConfigurationHelper.getIntProperty(erroneousReplica+".replica.port"));
				ri.resetErrorCount();
			}
			
		} 
		else {
			System.out.print("Cannot handle this type of message");
		}
	}
	
	public void syncFaultyReplica(String replicaHost, int replicaPort){
		
		SyncLibraryDatabaseMessage message = new SyncLibraryDatabaseMessage();
		try {
			UdpClient toReplica = new UdpClient(replicaHost, replicaPort);
			System.out.println("Sending request to restart REPLICA HOST: " +replicaHost + "@PORT: " +replicaPort);
			toReplica.send(message);
		} catch (SocketException | UnknownHostException e) {
			System.out.println("Error: " +e.getMessage());
			e.printStackTrace();
		} 	
	}
	
	public static void main(String[] args) {
		CommandClient.printHeader("Replica Manager");

		ReplicaManagerUdpServer rm = new ReplicaManagerUdpServer();
		rm.startUDPServer();

	}
	
	

}
